package com.example.leetcode.c1_c100.c59;
/**
 * 给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。
 *
 * 示例:
 *
 * 输入: 3
 * 输出:
 * [
 *  [ 1, 2, 3 ],
 *  [ 8, 9, 4 ],
 *  [ 7, 6, 5 ]
 * ]
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/spiral-matrix-ii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */

/**
 * 螺旋矩阵 II
 * @author zhanpengguo
 * @date 2020-09-15 8:19
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] ints = solution.generateMatrix(5);
        for (int i = 0; i < ints.length; i++) {
            for (int j = 0; j < ints[i].length; j++) {
                System.out.print(ints[i][j] + "\t");
            }
            System.out.println();
        }
    }

    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int top = 0;
        int right = n - 1;
        int down = n - 1;
        int left = 0;
        int i = 1;
        while (i <= n * n) {
            for (int j = left; j <= right; j++) {
                res[top][j] = i;
                i++;
            }
            top++;
            for (int j = top; j <= down; j++) {
                res[j][right] = i;
                i++;
            }
            right--;
            for (int j = right; j >= left; j--) {
                res[down][j] = i;
                i++;
            }
            down--;
            for (int j = down; j >= top; j--) {
                res[j][left] = i;
                i++;
            }
            left++;
        }
        return res;
    }
}
